<template>
  <div class="page-container">
    <div class="info-container">
      <div class="info-container_header">
        <div class="title">{{ title }}</div>
      </div>
      <div class="info-container_body">
        <el-form ref="refFrom" label-position="top" :model="form.model" class="demo">
          <div class="form-section">
            <div class="form-section_title">基础信息</div>
            <AgelFormGrid :items="form.baseItems" :span="6" :gutter="16">
              <template #slot-map>
                <MapInput v-model="form.model['location']" @change="mapChange"></MapInput>
              </template>
            </AgelFormGrid>
          </div>
          <div class="form-section">
            <div class="form-section_title">参数设置</div>
            <AgelFormGrid :items="form.propItems" :span="6" :gutter="16">
              <template #slot-leakThreshold>
                <el-input v-model="form.model['leakThreshold']" placeholder="最低保压时长(小时)" clearable />
              </template>
            </AgelFormGrid>
          </div>
          <div class="form-section">
            <div class="form-section_title">电费结算模式</div>
            <AgelFormGrid :items="form.eleItems" :span="6" :gutter="16"> </AgelFormGrid>
          </div>
          <div class="form-section" v-if="orderId">
            <div class="form-section_title">施工图</div>
            <UploadImage v-model="form.model.attachments" :queryData="{ stationId: orderId, name: '施工图' }"> </UploadImage>
          </div>
        </el-form>
      </div>
      <div class="info-container_footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { addStation, updateStation, getStation } from '@/api/station/index';
import { StationVO, StationForm, defaultStationModel } from '@/api/station/types';
import UploadImage from '../common/upload-image/index.vue';
import RegionSelect from '@/components/RegionSelect/index.vue';
import MapInput from '@/components/MapInput/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { epay_type, esettle_type } = toRefs<any>(proxy?.useDict('esettle_type', 'epay_type'));

const route = useRoute();
const orderId = toRef<string | null>(route.query.id as string);
const title = computed(() => {
  return orderId.value ? '编辑站房' : '新增站房';
});

const form = reactive({
  model: defaultStationModel(),
  baseItems: [
    { prop: 'name', label: '站房名称', required: true },
    { prop: 'contactUser', label: '商务联系人', required: true },
    { prop: 'contactPhone', label: '联系人电话”', required: true },
    { prop: 'regionCode', label: '省市区', slot: RegionSelect, required: true },
    { prop: 'location', label: '具体地址', slot: 'slot-map', span: 12, required: true }
  ],
  propItems: [
    { prop: 'maxCap', label: '最大接入数量', attrs: { type: 'number' }, required: true },
    { prop: 'pmax', label: '站房压力上限(帕)', attrs: { type: 'number' }, required: true },
    { prop: 'pmin', label: '站房压力下限(帕)', attrs: { type: 'number' }, required: true },
    { prop: 'omax', label: '浓度上限(%)', attrs: { type: 'number' }, required: true },
    { prop: 'omin', label: '浓度下限(%)', attrs: { type: 'number' }, required: true },
    { prop: 'eprice', label: '单位电价(元)', attrs: { type: 'number' }, required: true },
    { prop: 'leakThreshold', label: '最低保压时长(小时)', attrs: { type: 'number' }, required: true, slot: 'slot-leakThreshold' },
    { prop: 'plowDays', label: '持续欠压天数(天)', attrs: { type: 'number' }, required: true },
    { prop: 'softExpansion', label: '软扩容', slot: 'el-switch', attrs: { activeValue: 1, inactiveValue: 0 } },
    { prop: 'operationalMode', label: '调试模式', slot: 'el-switch', attrs: { activeValue: '1', inactiveValue: '0' } },
    { prop: 'runReportPeriod', label: '运行状态上报周期(秒)', attrs: { type: 'number' }, required: true, default: 60 },
    { prop: 'stopReportPeriod', label: '停止状态上报周期(秒)', attrs: { type: 'number' }, required: true, default: 600 }
  ],
  eleItems: [
    {
      prop: 'epayType',
      label: '类型',
      slot: 'agel-select',
      required: true,
      attrs: {
        options: epay_type
      }
    },
    {
      prop: 'esettleType',
      label: '结算模式',
      slot: 'agel-radio',
      attrs: {
        options: esettle_type
      }
    }
    // { prop: "esettleVendor", label: "商户名称" },
  ],
  fileItems: [{ prop: 'attachments', label: '添加图片', span: 24 }]
});
const loading = ref(false);
const refFrom = ref<ElFormInstance>();

const mapChange = (val: any) => {
  console.log('mapChange', val);
};
/** 取消 */
const handleCancel = () => {
  // proxy?.$tab.closeOpenPage()
  proxy?.$tab.closePage();
};
/** 确认 */
const handleSubmit = async () => {
  if (!refFrom.value) return;
  refFrom.value.validate((valid, fields) => {
    if (valid) {
      requestAdd();
    } else {
      console.log('error submit!', fields);
    }
  });
};
const getInfo = async (id: string) => {
  loading.value = true;
  let res = await getStation(id);
  loading.value = false;
  if (res.code == 200) {
    let item = res.data;
    item.leakThreshold /= 60 * 60;
    item.omin /= 10.0;
    item.omax /= 10.0;

    form.model = item;
  } else {
    proxy?.$modal.msgError(res.msg || '信息获取失败！');
  }
};
const requestAdd = async () => {
  let serviceHandle = orderId.value ? updateStation : addStation;
  loading.value = true;
  let item = JSON.parse(JSON.stringify(form.model as StationForm));
  item.leakThreshold *= 60 * 60;
  item.omin *= 10.0;
  item.omax *= 10.0;
  let res = await serviceHandle(item);
  loading.value = false;
  if (res.code == 200) {
    proxy?.$modal.msgSuccess('操作成功！');
    proxy?.$tab.closeOpenPage('/station/stationMessage');
  } else {
    proxy?.$modal.msgError(res.msg || '操作失败！');
  }
};

if (orderId.value) {
  getInfo(orderId.value);
} else {
  form.model.runReportPeriod = 60;
  form.model.stopReportPeriod = 600;
}
onMounted(() => {});
</script>
